<?php
$lico = array();

date_default_timezone_set('Europe/Berlin');


/*
header('X-LiCo-Author: Alexander Löhner');
header('X-LiCo-Author-Website: http://about.me/loehner');
header('X-LiCo-Email: info@linuxcounter.net');
header('X-LiCo-Bugtracker: http://trac.linuxcounter.net/');
header('X-LiCo-Copyright: Alexander Löhner');
*/


/** 
* ALL Notices, Warnings and errors will be showed 
*/
error_reporting(E_ALL & ~E_NOTICE);
ini_set('display_errors', 'Off');


if (isset($_COOKIE['isadmin']) && intval($_COOKIE['isadmin']) == 1) {
  error_reporting(E_ALL & ~E_NOTICE);
  ini_set('display_errors', 'On');
}



ini_set('browscap', '/etc/browsecap.ini');

/** 
* Set max_execution_time to 60 seconds 
*/
@set_time_limit(60);


/** 
* Set magic_quotes_runtime to off
*/
@ini_set('magic_quotes_runtime', 'off');


@define('IN_linuxcounter', true);
@define('IN_lico', true);
@define('IS_installed', true);
@define('IS_uptodate', true);
$lastpointpos = strrpos($_SERVER['PHP_SELF'], ".");
$SUFFIX = substr($_SERVER['PHP_SELF'], ($lastpointpos+1), strlen($_SERVER['PHP_SELF']));
$error = array();
$success = array();

$proto = "http";
if (isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == 443) { $proto .= "s"; }

/**  setting own protocol  **/
if (!defined('APN_URL')) {
  define('APN_PROTO', $proto);
}

$mainurl = $proto."://".(isset($_SERVER['HTTP_HOST'])?$_SERVER['HTTP_HOST']:"linuxcounter.net");
if (isset($_SERVER['SCRIPT_NAME']) && trim($_SERVER['SCRIPT_NAME']) != "")
  $script = trim($_SERVER['SCRIPT_NAME']);
elseif (isset($_SERVER['PHP_SELF']) && trim($_SERVER['PHP_SELF']) != "")
  $script = trim($_SERVER['PHP_SELF']);
$tmp = explode("index.php", $script);
$mainurl .= $tmp[0];

if (!isset($_REQUEST)) {
    $_REQUEST = &$HTTP_REQUEST_VARS;
}
if (!isset($_POST)) {
    $_POST = &$HTTP_POST_VARS;
}
if (!isset($_GET)) {
    $_GET = &$HTTP_GET_VARS;
}
if (!isset($_SESSION)) {
    $_SESSION = &$HTTP_SESSION_VARS;
}
if (!isset($_COOKIE)) {
    $_COOKIE = &$HTTP_COOKIE_VARS;
}
if (!isset($_SERVER)) {
    $_SERVER = &$HTTP_SERVER_VARS;
}
if (extension_loaded('filter') && filter_id(ini_get('filter.default')) !== FILTER_UNSAFE_RAW) {
    foreach ($_POST as $key => $value) {
        $_POST[$key] = input_get(INPUT_POST, $key, FILTER_UNSAFE_RAW);
    }
    foreach ($_GET as $key => $value) {
        $_GET[$key] = input_get(INPUT_GET, $key, FILTER_UNSAFE_RAW);
    }
    foreach ($_COOKIE as $key => $value) {
        $_COOKIE[$key] = input_get(INPUT_COOKIE, $key, FILTER_UNSAFE_RAW);
    }
    foreach ($_SESSION as $key => $value) {
        $_SESSION[$key] = input_get(INPUT_SESSION, $key, FILTER_UNSAFE_RAW);
    }
}


/** 
* Merge GET vars into the lico array 
*/
$lico['GET']    = &$_GET['lico'];

/** 
* Merge POST vars into the lico array 
*/
$lico['POST']   = &$_POST['lico'];

/** 
* Merge COOKIE vars into the lico array 
*/
$lico['COOKIE'] = &$_COOKIE['lico'];



$PATH = @realpath(@dirname(__FILE__));
/** 
* Find and save the absolute server-path for later use 
*/
$lico['path'] = $PATH."/";
$lico['abs_path'] = $PATH."/";
$lico['sec_path'] = str_replace("/www/", "", $lico['abs_path'])."/";

/**  Getting and Setting real full url  **/
if (!isset($lico['full_url'])) {
  $lico['full_url'] = $mainurl;
}

if (!isset($lico['tool_path'])) {
  $lico['tool_path'] = $lico['abs_path'];
}

if (!isset($lico['temp_path'])) {
  $lico['temp_path'] = $lico['abs_path']."temp/";
}

if (!isset($lico['libs_path'])) {
  $lico['libs_path'] = $lico['tool_path']."libs/";
}

if (!isset($lico['lang_path'])) {
  $lico['lang_path'] = $lico['tool_path']."lang/";
}



$old_include = ini_get('include_path');
$new_include = ".:..:".$lico['abs_path'].":".$lico['tool_path'].":".$lico['libs_path'].":".$old_include;
@ini_set('include_path', $new_include);


/** 
* Attempt to fix IIS compatibility 
**/
if (empty($_SERVER['REQUEST_URI'])) {
    $_SERVER['REQUEST_URI'] = $_SERVER['SCRIPT_NAME'] . '?' . (!empty($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : '');
}


$actyear = date("Y", time());
if ($actyear==2011)
  $copyrightdate = 2011;
else
  $copyrightdate = "2011 - ".$actyear;


$path = $lico['abs_path'];

if (file_exists($lico['tool_path']."config.local.inc.php")) {
  /** 
  * Include of the user defined configuration 
  */
  include($lico['tool_path']."config.local.inc.php");
}

sort($lico['allowed_lang']);

$dst = date("I");
if ($dst == 1)
  $minus = 3600 * 2;
else
  $minus = 3600 * 1;
$aktts = gmmktime()-$minus;

include($lico['libs_path']."database.func.php");
include($lico['libs_path']."functions.lib.php");

$needlogin = array('machines', 'profile', 'public');
$exit = 0;
$iserror = 0;

$lico['mysql_prefix'] = $MYSQLDATA['PREFIX']."_";
$lico['table']['users']       = $lico['mysql_prefix']."user";

if (!isset($_SESSION['loggedin'])) {
  $_SESSION['loggedin'] = false;
}


if (isset($_GET['resend']) && intval($_GET['resend']) == 1) {
  $key = trim($_GET['ck']);
  $select = "SELECT * FROM `users` WHERE `credentials`='".lico_ESC($key)."'";
  $seluser = $db->unbuffered_query_first($select);
  if (!isset($seluser[0]) || intval($seluser[0]) <= 0) {
    $error[] = lico_lang('general', 'user.unknown');
    $iserror = 1;
  } else {
    $confirmkey = lico_GenRandomString(48, PWD_ALLOW_ALL);
    $upd = "UPDATE `users` SET `f_mtime`='".date("Y-m-d H:i:s", time())."', `credentials`='".$confirmkey."' WHERE `credentials`='".lico_ESC($key)."'";
    $db->unbuffered_query($upd);
    
    $success[] = lico_lang('general', 'sent.confirmation.mail');
    
    $to = stripslashes(trim($seluser[5]));
    $betreff = lico_lang('general', 'confirmation.mail.subject');
    $text = lico_lang('general', 'confirmation.mail.body');
    $text = str_replace("#CONFIRMKEY#", $confirmkey, $text);
    
    $header = 'From: "LinuxCounter.net" <noreply@linuxcounter.net>' . "\r\n" .
        'Reply-To: info@linuxcounter.net' . "\r\n" .
        'X-Mailer: PHP/' . phpversion();
    mail("$to", "$betreff", "$text", "$header");
  }
}

if (isset($lico['POST']['logout']) && intval($lico['POST']['logout']) == 1) {
  unset($lico['COOKIE']['pwd']);
  unset($lico['COOKIE']['num']);
  unset($lico['user']);
  unset($_SESSION['email']);
  $_SESSION['loggedin'] = false;
  $_SESSION['userid'] = 0;
  if (!isset($_SESSION['lang'])) {
    $_SESSION['lang'] = lico_getLangfromBrowser();
  }
  lico_delcookies();
  $success[] = lico_lang('general', 'successfully.logged.out');
}





$error = array("Testing...");



if (isset($lico['POST']['login']) && intval($lico['POST']['login']) == 1) {
  $password = md5(trim($lico['POST']['password']));
  $userid = trim($lico['POST']['number']);
  if (is_numeric($userid)) {
    $where = "f_key";
  } else {
    $where = "username";
  }
  
  $select = "SELECT * FROM `users` WHERE `".$where."`='".lico_ESC($userid)."'";
  $seluser = $db->unbuffered_query_first($select);
  if (isset($seluser[0]) && intval($seluser[0]) >= 1) {
    if ($seluser[7] == 0) {
      $text = lico_lang('general', 'not.activated.account');
      $text = str_replace("#CONFIRMKEY#", $seluser[9], $text);
      unset($lico['COOKIE']['pwd']);
      unset($lico['COOKIE']['num']);
      unset($lico['user']);
      unset($_SESSION['email']);
      $_SESSION['loggedin'] = false;
      $_SESSION['userid'] = 0;
      $_SESSION['username'] = '';
      if (!isset($_SESSION['lang'])) {
        $_SESSION['lang'] = lico_getLangfromBrowser();
      }
      lico_delcookies();
      $error[] = $text;
      $iserror = 1;
    } else if ($seluser[7] == 99) {
      $text = lico_lang('general', 'account.deleted');
      $text = str_replace("#CONFIRMKEY#", $seluser[9], $text);
      unset($lico['COOKIE']['pwd']);
      unset($lico['COOKIE']['num']);
      unset($lico['user']);
      unset($_SESSION['email']);
      $_SESSION['loggedin'] = false;
      $_SESSION['userid'] = 0;
      $_SESSION['username'] = '';
      if (!isset($_SESSION['lang'])) {
        $_SESSION['lang'] = lico_getLangfromBrowser();
      }
      lico_delcookies();
      $error[] = $text;
      $iserror = 1;
    } elseif (trim($seluser[6]) != $password) {
      unset($lico['COOKIE']['pwd']);
      unset($lico['COOKIE']['num']);
      unset($lico['user']);
      unset($_SESSION['email']);
      $_SESSION['loggedin'] = false;
      $_SESSION['userid'] = 0;
      $_SESSION['username'] = '';
      if (!isset($_SESSION['lang'])) {
        $_SESSION['lang'] = lico_getLangfromBrowser();
      }
      lico_delcookies();
      $error[] = lico_lang('general', 'wrong.password');
      $iserror = 1;
    } else {
      
      if ($seluser[7] == 2) {
        lico_SetUserState(intval($seluser[0]), 1);
        $text = lico_lang('general', 'account.freezed');
        $text = str_replace("#CONFIRMKEY#", $seluser[9], $text);
        $error[] = $text;
        $iserror = 0;
      }
      
      $selp = "SELECT * FROM `persons` WHERE `f_key`='".lico_ESC($seluser[0])."'";
      $retp = $db->unbuffered_query_first($selp);
      if (!isset($retp[0]) || intval($retp[0]) <= 0) {
        $insert = "INSERT INTO `persons` SET `f_key`='".intval($seluser[0])."'";
        $db->unbuffered_query($insert);
      }
      
      
      
      $selup = "SELECT * FROM `user_pref` WHERE `f_key`='".lico_ESC($seluser[0])."'";
			$retup = $db->getAll_assoc($selup);
			if (count($retup) >= 1) {
				for ($cup=0; $cup<count($retup); $cup++) {
					$variable = trim($retup[$cup]['variable']);
					$value    = trim($retup[$cup]['value']);
					if (is_numeric($value)) {
					  $value = intval($value);
			    } else {
			      $value = trim(stripslashes($value));
	        }
					$lico['user'][$variable] = $value;
				}
			}
      
      $lico['user']['id'] = intval($seluser[0]);
      $lico['user']['email'] = trim($seluser[5]);
      $lico['user']['password'] = trim($seluser[6]);
      $lico['user']['username'] = stripslashes(trim($seluser[15]));
      $lang = strtolower(trim($seluser[12]));
      if (!isset($_SESSION['lang'])) {
        $_SESSION['lang'] = $lang;
      }
      $_SESSION['email'] = $lico['user']['email'];
      $_SESSION['isloggedin'] = true;
      $_SESSION['userid'] = intval($seluser[0]);
      $_SESSION['username'] = trim($seluser[15]);
      $success[] = lico_lang('general', 'login.successful');
      $db->unbuffered_query("UPDATE `users` SET `logintime`='".date("Y-m-d H:i:s", time())."' WHERE `f_key`='".intval($seluser[0])."';");
      if (isset($lico['POST']['merken']) && intval($lico['POST']['merken']) == 1) {
        setcookie("lico[pwd]", trim($password), time()+(86400*365), "/");
        setcookie("lico[num]", trim($seluser[0]), time()+(86400*365), "/");
      } else {
        setcookie("lico[pwd]", trim($password), 0, "/");
        setcookie("lico[num]", trim($seluser[0]), 0, "/");
      }

      $lico['COOKIE']['pwd'] = $password;
    }
  } else {
    unset($lico['COOKIE']['pwd']);
    unset($lico['COOKIE']['num']);
    unset($lico['user']);
    unset($_SESSION['email']);
    $_SESSION['loggedin'] = false;
    $_SESSION['userid'] = 0;
    $_SESSION['username'] = '';
    if (!isset($_SESSION['lang'])) {
      $_SESSION['lang'] = lico_getLangfromBrowser();
    }
    lico_delcookies();
    $error[] = lico_lang('general', 'user.unknown');
    $iserror = 1;
  }
}




require($lico['libs_path']."lightopenid/openid.php");
$thisopenid = new LightOpenID('linuxcounter.net');


if ($_SESSION['loggedin'] === false) {
  
  if((isset($_GET['a']) && trim($_GET['a']) == "google")) {
    if (isset($lico['POST']['merken']) && intval($lico['POST']['merken']) == 1) {
      setcookie("lico[merken]", 1, 0, "/");
    }
    setcookie("lico[openid_service]", trim($_GET['a']), 0, "/");
    if(!$thisopenid->mode) {
      $thisopenid->identity = 'https://www.google.com/accounts/o8/id';
      $thisopenid->required = array('namePerson/friendly', 'contact/email', 'contact/country/home', 'pref/timezone', 'pref/language');
      header('Location: '.$thisopenid->authUrl());
      exit;
    }
  }
  
  
  
  if ((isset($lico['POST']['openid']) && intval($lico['POST']['openid']) == 1) && (isset($lico['POST']['service']) && trim($lico['POST']['service']) != "")) {
    $username = trim($lico['POST']['openidusername']);
    if (isset($lico['POST']['merken']) && intval($lico['POST']['merken']) == 1) {
      setcookie("lico[merken]", 1, 0, "/");
    }
    setcookie("lico[openid_service]", trim($lico['POST']['service']), 0, "/");
    if(!$thisopenid->mode) {
      $thisopenid->identity = $username;
      $thisopenid->required = array('namePerson/friendly', 'contact/email', 'contact/country/home', 'pref/timezone', 'pref/language');
      header('Location: '.$thisopenid->authUrl());
      exit;
    }
  }
  
  
  
  if (isset($thisopenid->mode) && $thisopenid->mode == 'cancel') {
    unset($lico['COOKIE']['pwd']);
    unset($lico['COOKIE']['num']);
    unset($lico['user']);
    unset($_SESSION['email']);
    $_SESSION['loggedin'] = false;
    $_SESSION['userid'] = 0;
    $_SESSION['username'] = '';
    if (!isset($_SESSION['lang'])) {
      $_SESSION['lang'] = lico_getLangfromBrowser();
    }
    lico_delcookies();
    $iserror = 1;
    $error[] = lico_lang('general', 'openid.cancelled');
    
  } else {
    if ($thisopenid->validate()) {
      
      if (isset($lico['COOKIE']['openid']) && trim($lico['COOKIE']['openid']) != "") {
        $openidurl = trim($lico['COOKIE']['openid']);
        unset($lico['COOKIE']['openid']);
      } else {
        $openidurl = $thisopenid->identity;
      }
      $userdata = $thisopenid->getAttributes();
      $email = trim($userdata['contact/email']);
      
      $select = "SELECT * FROM `openid` WHERE `url`='".lico_ESC($openidurl)."' AND `service`='".lico_ESC($lico['COOKIE']['openid_service'])."'";
      $selopenid = $db->unbuffered_query_first($select);
      
      if (isset($selopenid[0]) && intval($selopenid[0]) >= 1) {
        
        $select = "SELECT * FROM `users` WHERE `f_key`='".lico_ESC($selopenid[1])."'";
        $seluser = $db->unbuffered_query_first($select);
        
        if (isset($seluser[0]) && intval($seluser[0]) >= 1) {
          if ($seluser[7] == 0) {
            $text = lico_lang('general', 'not.activated.account');
            $text = str_replace("#CONFIRMKEY#", $seluser[9], $text);
            unset($lico['COOKIE']['pwd']);
            unset($lico['COOKIE']['num']);
            unset($lico['user']);
            unset($_SESSION['email']);
            $_SESSION['loggedin'] = false;
            $_SESSION['userid'] = 0;
            $_SESSION['username'] = '';
            if (!isset($_SESSION['lang'])) {
              $_SESSION['lang'] = lico_getLangfromBrowser();
            }
            lico_delcookies();
            $error[] = $text;
            $iserror = 1;
          } else if ($seluser[7] == 99) {
            $text = lico_lang('general', 'account.deleted');
            $text = str_replace("#CONFIRMKEY#", $seluser[9], $text);
            unset($lico['COOKIE']['pwd']);
            unset($lico['COOKIE']['num']);
            unset($lico['user']);
            unset($_SESSION['email']);
            $_SESSION['loggedin'] = false;
            $_SESSION['userid'] = 0;
            $_SESSION['username'] = '';
            if (!isset($_SESSION['lang'])) {
              $_SESSION['lang'] = lico_getLangfromBrowser();
            }
            lico_delcookies();
            $error[] = $text;
            $iserror = 1;
          } else {
            
            if ($seluser[7] == 2) {
              lico_SetUserState(intval($seluser[0]), 1);
              $text = lico_lang('general', 'account.freezed');
              $text = str_replace("#CONFIRMKEY#", $seluser[9], $text);
              $error[] = $text;
              $iserror = 0;
            }
            
            $selp = "SELECT * FROM `persons` WHERE `f_key`='".lico_ESC($seluser[0])."'";
            $retp = $db->unbuffered_query_first($selp);
            if (!isset($retp[0]) || intval($retp[0]) <= 0) {
              $insert = "INSERT INTO `persons` SET `f_key`='".intval($seluser[0])."'";
              $db->unbuffered_query($insert);
            }
            
            $selup = "SELECT * FROM `user_pref` WHERE `f_key`='".lico_ESC($seluser[0])."'";
    				$retup = $db->getAll_assoc($selup);
    				if (count($retup) >= 1) {
      				for ($cup=0; $cup<count($retup); $cup++) {
      					$variable = trim($retup[$cup]['variable']);
      					$value    = trim($retup[$cup]['value']);
      					if (is_numeric($value)) {
      					  $value = intval($value);
    				    } else {
    				      $value = trim(stripslashes($value));
    		        }
      					$lico['user'][$variable] = $value;
     					}
    				}
            
            $lico['user']['id'] = intval($seluser[0]);
            $lico['user']['email'] = trim($seluser[5]);
            $lico['user']['password'] = trim($seluser[6]);
            $lico['user']['username'] = stripslashes(trim($seluser[15]));
            $lang = strtolower(trim($seluser[12]));
            if (!isset($_SESSION['lang'])) {
              $_SESSION['lang'] = $lang;
            }
            $_SESSION['email'] = $lico['user']['email'];
            $_SESSION['isloggedin'] = true;
            $_SESSION['userid'] = intval($seluser[0]);
            $_SESSION['username'] = trim($seluser[15]);
            $success[] = lico_lang('general', 'login.successful');
            $db->unbuffered_query("UPDATE `users` SET `logintime`='".date("Y-m-d H:i:s", time())."' WHERE `f_key`='".intval($seluser[0])."';");
            if (isset($lico['COOKIE']['merken']) && intval($lico['COOKIE']['merken']) == 1) {
              setcookie("lico[merken]", "", (time()-86400));
              setcookie("lico[pwd]", trim($seluser[6]), time()+(86400*365), "/");
              setcookie("lico[num]", trim($seluser[0]), time()+(86400*365), "/");
            } else {
              setcookie("lico[pwd]", trim($seluser[6]), 0, "/");
              setcookie("lico[num]", trim($seluser[0]), 0, "/");
            }
            $lico['COOKIE']['pwd'] = trim($seluser[6]);
            $lico['COOKIE']['num'] = trim($seluser[0]);
          }
        }
      } else {
        
        $_SESSION['openidurl'] = $openidurl;
        $_SESSION['userdata'] = $userdata;
        $_SESSION['email'] = $email;
        $_SESSION['service'] = $lico['COOKIE']['openid_service'];
        
        header('Location: '.$lico['baseurl.ssl'].'/openidreg.html');
        exit;
      }
    }
  }
} else {

  if(isset($_GET['a']) && trim($_GET['a']) == "google") {
    setcookie("lico[openid_service]", trim($_GET['a']), 0, "/");
    if(!$thisopenid->mode) {
      $thisopenid->identity = 'https://www.google.com/accounts/o8/id';
      $thisopenid->required = array('namePerson/friendly', 'contact/email', 'contact/country/home', 'pref/timezone', 'pref/language');
      header('Location: '.$thisopenid->authUrl());
      exit;
    }
  }
  
  if ((isset($lico['POST']['openid']) && intval($lico['POST']['openid']) == 1) && (isset($lico['POST']['service']) && trim($lico['POST']['service']) != "")) {
    $username = trim($lico['POST']['openidusername']);
    if (isset($lico['POST']['merken']) && intval($lico['POST']['merken']) == 1) {
      setcookie("lico[merken]", 1, 0, "/");
    }
    setcookie("lico[openid_service]", trim($lico['POST']['service']), 0, "/");
    setcookie("lico[openid]", $username, 0, "/");
    if(!$thisopenid->mode) {
      $thisopenid->identity = $username;
      $thisopenid->required = array('namePerson/friendly', 'contact/email', 'contact/country/home', 'pref/timezone', 'pref/language');
      header('Location: '.$thisopenid->authUrl());
      exit;
    }
  }
  
  
  if ($thisopenid->validate()) {
    
    if (isset($lico['COOKIE']['openid']) && trim($lico['COOKIE']['openid']) != "") {
      $openidurl = trim($lico['COOKIE']['openid']);
      unset($lico['COOKIE']['openid']);
    } else {
      $openidurl = $thisopenid->identity;
    }
    $userdata = $thisopenid->getAttributes();
    $email = trim($userdata['contact/email']);
    
/**
    $openidurl = https://www.google.com/accounts/o8/id?id=AItOawldfv76HEVnLT3a5dItlC_g1q9wezQ_Ws0
    $userdata[contact/email] =  alex.mieland@googlemail.com
    $userdata[pref/language] =  de
    $userdata[contact/country/home] =  DE
**/
    
    $select = "SELECT * FROM `openid` WHERE `owner`='".lico_ESC($_SESSION['userid'])."' AND `url`='".lico_ESC($openidurl)."' AND `service`='".lico_ESC($lico['COOKIE']['openid_service'])."'";
    $selopenid = $db->unbuffered_query_first($select);
    
    if (isset($selopenid[0]) && intval($selopenid[0]) >= 1) {
      
    } else {
      
      $ins1 = "INSERT INTO openid SET `owner`='".lico_ESC($_SESSION['userid'])."', `url`='".lico_ESC($openidurl)."', `service`='".lico_ESC($lico['COOKIE']['openid_service'])."'";
      $db->unbuffered_query($ins1);
      
      header('Location: '.$lico['baseurl.ssl'].'/profile/openid.html#openid');
      exit;
    }
  }
}







// confirmed new registration with openid
if (isset($_GET['a']) && trim($_GET['a']) == "regconfirm") {
  
  $openidurl = $_SESSION['openidurl'];
  $userdata = $_SESSION['userdata'];
  $email = $_SESSION['email'];
  $service = $_SESSION['service'];
  $lang = "en";
  
  unset($seluser);
  $select = "SELECT * FROM `users` WHERE `email`='".lico_ESC($email)."'";
  $seluser = $db->unbuffered_query_first($select);
  if (isset($seluser[0]) && intval($seluser[0]) >= 1) {
    $error[] = lico_lang('general', 'openid.email.already.taken');
    $iserror = 1;
  } else {
    

/**
$openidurl = https://www.google.com/accounts/o8/id?id=AItOawldfv76HEVnLT3a5dItlC_g1q9wezQ_Ws0
$userdata[contact/email] =  alex.mieland@googlemail.com
$userdata[pref/language] =  de
$userdata[contact/country/home] =  DE
**/

    $newpasswd = lico_GenRandomString(16, PWD_ALLOW_ALL);
    $cnewpasswd = md5($newpasswd);
    
    $insert = "INSERT INTO `users` SET `f_ctime`='".date("Y-m-d H:i:s", time())."', `email`='".addslashes($email)."', `lang`='".$lang."', `login`='".lico_ESC($cnewpasswd)."', `credentials`='', `state`=1";
    $db->unbuffered_query($insert);
    
    $select = "SELECT `f_key` FROM `users` WHERE `email`='".lico_ESC($email)."' AND `login`='".lico_ESC($cnewpasswd)."'";
    $seluser = $db->unbuffered_query_first($select);
    
    lico_SetUserState(intval($seluser[0]), 1);
    
    $insert = "INSERT INTO `persons` SET `f_key`='".intval($seluser[0])."'";
    $db->unbuffered_query($insert);
    
    $ins1 = "INSERT INTO openid SET `owner`='".lico_ESC($seluser[0])."', `url`='".lico_ESC($openidurl)."', `service`='".lico_ESC($service)."'";
    $db->unbuffered_query($ins1);
    
    $success[] = lico_lang('general', 'openid.thanks.for.registering');
    
    $to = $email;
    $betreff = lico_lang('general', 'openid.reg.email.subject');
    $text = lico_lang('general', 'openid.reg.email.body');
    $text = str_replace("#COUNTERNUM#", $seluser[0], $text);
    // $text = str_replace("#USERNAME#", $username, $text);
    $text = str_replace("#PASSWORD#", $newpasswd, $text);
    $header = 'From: "LinuxCounter.net" <noreply@linuxcounter.net>' . "\r\n" .
        'Reply-To: info@linuxcounter.net' . "\r\n" .
        'X-Mailer: PHP/' . phpversion();
    mail("$to", "$betreff", "$text", "$header");
    if ($lico['send.admin.mails'] === true) {
      for ($a=0; $a<count($lico['adminmails']); $a++) {
          mail($lico['adminmails'][$a], "[lico] New OpenID Registration for \"".$email."\"", "Hello admin,\n".$email." has just registered a new account (Counter num: ".$seluser[0].").\n", "$header");
      }
    }
    $success[] = lico_lang('general', 'openid.registration.successful');
    $db->unbuffered_query("UPDATE `users` SET `logintime`='".date("Y-m-d H:i:s", time())."' WHERE `f_key`='".intval($seluser[0])."';");
    
    $lico['user']['id'] = intval($seluser[0]);
    $lico['user']['email'] = trim($seluser[5]);
    $lico['user']['password'] = trim($seluser[6]);
    $lico['user']['username'] = stripslashes(trim($seluser[15]));
    $lang = strtolower(trim($seluser[12]));
    if (!isset($_SESSION['lang'])) {
      $_SESSION['lang'] = $lang;
    }
    $_SESSION['email'] = $lico['user']['email'];
    $_SESSION['isloggedin'] = true;
    $_SESSION['userid'] = intval($seluser[0]);
    $_SESSION['username'] = trim($seluser[15]);
    if (isset($lico['COOKIE']['merken']) && intval($lico['COOKIE']['merken']) == 1) {
      setcookie("lico[merken]", "", (time()-86400));
      setcookie("lico[pwd]", trim($seluser[6]), time()+(86400*365), "/");
      setcookie("lico[num]", trim($seluser[0]), time()+(86400*365), "/");
    } else {
      setcookie("lico[pwd]", trim($seluser[6]), 0, "/");
      setcookie("lico[num]", trim($seluser[0]), 0, "/");
    }
    $lico['COOKIE']['pwd'] = trim($seluser[6]);
    $lico['COOKIE']['num'] = trim($seluser[0]);
    
  }
  
}









if (isset($_GET['activate']) && trim($_GET['activate']) != "") {
  $select = "SELECT * FROM `users` WHERE `credentials`='".lico_ESC($_GET['activate'])."'";
  $seluser = $db->unbuffered_query_first($select);
  if (isset($seluser[0]) && intval($seluser[0]) >= 1) {
    if (intval($seluser[7]) == 1) {
      $success[] = lico_lang('general', 'account.already.activated');
    } else {
      $select = "SELECT `f_key` FROM `users` WHERE `credentials`='".lico_ESC($_GET['activate'])."'";
      $seluser = $db->unbuffered_query_first($select);
      
      $upd = "UPDATE `users` SET `f_mtime`='".date("Y-m-d H:i:s", time())."', `state`=1, `credentials`='' WHERE `f_key`='".lico_ESC($seluser[0])."'";
      $db->unbuffered_query($upd);
      
      lico_SetUserState(intval($seluser[0]), 1);
      
      $success[] = lico_lang('general', 'account.successfully.activated');
      $to = trim($seluser[5]);
      $username = trim($seluser[15]);
      $betreff = lico_lang('general', 'new.counternum.subject');
      $text = lico_lang('general', 'new.counternum.body');
      $text = str_replace("#COUNTERNUM#", intval($seluser[0]), $text);
      $text = str_replace("#USERNAME#", $username, $text);
      $header = 'From: "LinuxCounter.net" <noreply@linuxcounter.net>' . "\r\n" .
          'Reply-To: info@linuxcounter.net' . "\r\n" .
          'X-Mailer: PHP/' . phpversion();
      mail("$to", "$betreff", "$text", "$header");
      if ($lico['send.admin.mails'] === true) {
        for ($a=0; $a<count($lico['adminmails']); $a++) {
            mail($lico['adminmails'][$a], "[lico] New Registration for \"".$seluser[5]."\" (confirmed)", "Hello admin,\n".$seluser[5]." has just activated his account.\n", "$header");
        }
      }
    }
  } else {
    $iserror = 1;
    $error[] = lico_lang('general', 'registration.not.found');
  }
}









if (isset($lico['POST']['register']) && intval($lico['POST']['register']) == 1) {
  $username = trim($lico['POST']['username']);
  $password1 = md5(trim($lico['POST']['password1']));
  $password2 = md5(trim($lico['POST']['password2']));
  if ($password1 != $password2) {
    $error[] = lico_lang('general', 'passwords.do.not.match');
    $iserror = 1;
  } else {
    $select = "SELECT * FROM `users` WHERE `email`='".lico_ESC($lico['POST']['email'])."'";
    $seluser = $db->unbuffered_query_first($select);
    if (isset($seluser[0]) && intval($seluser[0]) >= 1) {
      $error[] = lico_lang('general', 'email.already.taken');
      $iserror = 1;
    } else if (!lico_ValidateEmail($lico['POST']['email'])) {
      $error[] = lico_lang('general', 'email.wrong');
      $iserror = 1;
    } else {
      $select = "SELECT * FROM `users` WHERE `username`='".lico_ESC($username)."'";
      $selusern = $db->unbuffered_query_first($select);
      if (isset($selusern[0]) && intval($selusern[0]) >= 1) {
        $error[] = lico_lang('general', 'username.exists');
        $iserror = 1;
      } else {
        $confirmkey = lico_GenRandomString(48, PWD_ALLOW_ALL);
        $insert = "INSERT INTO `users` SET `f_ctime`='".date("Y-m-d H:i:s", time())."', `email`='".addslashes(trim($lico['POST']['email']))."', `login`='".lico_ESC($password1)."', `credentials`='".lico_ESC($confirmkey)."', `state`=0, `username`='".lico_ESC($username)."'";
        $db->unbuffered_query($insert);
        
        $select = "SELECT `f_key` FROM `users` WHERE `email`='".lico_ESC($lico['POST']['email'])."' AND `credentials`='".lico_ESC($confirmkey)."'";
        $seluser = $db->unbuffered_query_first($select);
        
        lico_SetUserState(intval($seluser[0]), 0);
        
        $insert = "INSERT INTO `persons` SET `f_key`='".intval($seluser[0])."'";
        $db->unbuffered_query($insert);
        
        $success[] = lico_lang('general', 'thanks.for.registering');
        
        $to = $lico['POST']['email'];
        $betreff = lico_lang('general', 'reg.email.subject');
        $text = lico_lang('general', 'reg.email.body');
        $text = str_replace("#CONFIRMKEY#", $confirmkey, $text);
        $text = str_replace("#COUNTERNUM#", $seluser[0], $text);
        $text = str_replace("#USERNAME#", $username, $text);
        $text = str_replace("#PASSWORD#",   trim($lico['POST']['password1']), $text);
        
        $header = 'From: "LinuxCounter.net" <noreply@linuxcounter.net>' . "\r\n" .
            'Reply-To: info@linuxcounter.net' . "\r\n" .
            'X-Mailer: PHP/' . phpversion();
        mail("$to", "$betreff", "$text", "$header");
        if ($lico['send.admin.mails'] === true) {
          for ($a=0; $a<count($lico['adminmails']); $a++) {
              mail($lico['adminmails'][$a], "[lico] New Registration for \"".$lico['POST']['email']."\" (unconfirmed)", "Hello admin,\n".$lico['POST']['email']." has just registered a new account.\n", "$header");
          }
        }
      }
    }
  }
}








if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] === false) {
  if (!isset($lico['COOKIE']) || !isset($lico['COOKIE']['pwd']) || !isset($lico['COOKIE']['num'])) {
    $_SESSION['loggedin'] = false;
    $_SESSION['userid'] = 0;
    $_SESSION['username'] = '';
    if (!$_SESSION['lang']) {
      $_SESSION['lang'] = lico_getLangfromBrowser();
    }
  } else {
    $_SESSION['loggedin'] = true;
    $password = trim($lico['COOKIE']['pwd']);
    $select = "SELECT * FROM `users` WHERE `f_key`='".lico_ESC($lico['COOKIE']['num'])."' AND `login`='".lico_ESC($password)."'";
    $seluser = $db->unbuffered_query_first($select);
    if (isset($seluser[0]) && intval($seluser[0]) >= 1) {
      if ($seluser[7] == 0) {
        $text = lico_lang('general', 'not.activated.account');
        $text = str_replace("#CONFIRMKEY#", $seluser[9], $text);
        $error[] = $text;
        $iserror = 1;
        $_SESSION['loggedin'] = false;
        lico_delcookies();
      } else if ($seluser[7] == 99) {
        $text = lico_lang('general', 'account.deleted');
        $text = str_replace("#CONFIRMKEY#", $seluser[9], $text);
        $error[] = $text;
        $iserror = 1;
        $_SESSION['loggedin'] = false;
        lico_delcookies();
      } else {
        if ($seluser[7] == 2) {
          
          lico_SetUserState(intval($seluser[0]), 1);
          
          $text = lico_lang('general', 'account.freezed');
          $text = str_replace("#CONFIRMKEY#", $seluser[9], $text);
          $error[] = $text;
          $iserror = 0;
        }
        $userid = intval($seluser[0]);
        $db->unbuffered_query("UPDATE `users` SET `logintime`='".date("Y-m-d H:i:s", time())."' WHERE `f_key`='".$userid."';");
        
        
        
        $selup = "SELECT * FROM `user_pref` WHERE `f_key`='".lico_ESC($seluser[0])."'";
				$retup = $db->getAll_assoc($selup);
				if (count($retup) >= 1) {
  				for ($cup=0; $cup<count($retup); $cup++) {
  					$variable = trim($retup[$cup]['variable']);
  					$value    = trim($retup[$cup]['value']);
  					if (is_numeric($value)) {
  					  $value = intval($value);
				    } else {
				      $value = trim(stripslashes($value));
		        }
  					$lico['user'][$variable] = $value;
 					}
				}
        
        
        
        $lico['user']['id'] = $userid;
        $lico['user']['password'] = stripslashes(trim($seluser[2]));
        $lico['user']['email'] = stripslashes(trim($seluser[3]));
        $lico['user']['username'] = stripslashes(trim($seluser[15]));
        $lang = strtolower(trim($seluser[12]));
        if (!$_SESSION['lang']) {
          $_SESSION['lang'] = $lang;
        }
        $_SESSION['email'] = $lico['user']['email'];
        $_SESSION['isloggedin'] = true;
        $_SESSION['userid'] = $userid;
        $_SESSION['username'] = trim($seluser[15]);
      }
    } else {
      unset($lico['COOKIE']['pwd']);
      unset($lico['COOKIE']['num']);
      unset($lico['user']);
      unset($_SESSION['email']);
      $_SESSION['loggedin'] = false;
      $_SESSION['userid'] = 0;
      $_SESSION['username'] = '';
      if (!$_SESSION['lang']) {
        $_SESSION['lang'] = lico_getLangfromBrowser();
      }
      lico_delcookies();
    }
  }
}


if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {
  $selup = "SELECT * FROM `user_pref` WHERE `f_key`='".lico_ESC($_SESSION['userid'])."'";
	$retup = $db->getAll_assoc($selup);
	if (count($retup) >= 1) {
		for ($cup=0; $cup<count($retup); $cup++) {
			$variable = trim($retup[$cup]['variable']);
			$value    = trim($retup[$cup]['value']);
			if (is_numeric($value)) {
			  $value = intval($value);
	    } else {
	      $value = trim(stripslashes($value));
      }
			$lico['user'][$variable] = $value;
		}
	}
}




if (!$_SESSION['lang']) {
  $_SESSION['lang'] = "en";
}



if (isset($_GET['setlang']) && in_array(strtolower(trim($_GET['setlang'])), $lico['allowed_lang'])) {
  $_SESSION['lang'] = strtolower(trim($_GET['setlang']));
  if ($_SESSION['loggedin'] === true) {
    $upd = "UPDATE `users` SET `f_mtime`='".date("Y-m-d H:i:s", time())."', `lang`='".$_SESSION['lang']."' WHERE `f_key`='".lico_ESC($_SESSION['userid'])."'";
    $db->unbuffered_query($upd);
  }
}





if (!isset($lico['user']['timezone'])   || trim($lico['user']['timezone']) == "")   { $lico['user']['timezone'] = 0; }
if (!isset($lico['user']['dateformat']) || trim($lico['user']['dateformat']) == "") { $lico['user']['dateformat'] = "d/m/Y"; }
if (!isset($lico['user']['timeformat']) || trim($lico['user']['timeformat']) == "") { $lico['user']['timeformat'] = "h:ia"; }






if (isset($lico['POST']['action']) && trim($lico['POST']['action']) == "newpasswd") {
  $userid = trim($lico['POST']['userid']);
  if (is_numeric($userid)) {
    $where = "f_key";
  } else {
    $where = "username";
  }
  if (!isset($lico['POST']['email']) || trim($lico['POST']['email']) == "") {
    $iserror = 1;
    $error[] = lico_lang('forgotten', 'email.not.entered');
  } else if (!isset($lico['POST']['userid']) || trim($lico['POST']['userid']) == "") {
    $iserror = 1;
    $error[] = lico_lang('forgotten', 'userid.not.entered');
  } else {
    $select = "SELECT * FROM `users` WHERE (`".$where."`='".lico_ESC($userid)."' AND `email`='".lico_ESC(trim($lico['POST']['email']))."') AND `".$where."`!=''";
    $seluser = $db->unbuffered_query_first($select);
    if (isset($seluser[0]) && intval($seluser[0]) >= 1) {
      $newpasswd = lico_GenRandomString(8, PWD_ALLOW_ALL);
      $cnewpasswd = md5($newpasswd);
      $db->unbuffered_query("UPDATE `users` SET `f_mtime`='".date("Y-m-d H:i:s", time())."', `login`='".lico_ESC($cnewpasswd)."' WHERE `f_key`='".intval($seluser[0])."';");
      $success[] = lico_lang('forgotten', 'new.password.sent');
      $to = trim($lico['POST']['email']);
      $username = $seluser[15];
      $betreff = lico_lang('forgotten', 'new.password.email.subject');
      $text = lico_lang('forgotten', 'new.password.email.body');
      $text = str_replace("#EMAIL#", intval($seluser[0]), $text);
      $text = str_replace("#USERNAME#", $username, $text);
      $text = str_replace("#PASSWORD#", $newpasswd, $text);
      $header = 'From: "LinuxCounter.net" <noreply@linuxcounter.net>' . "\r\n" .
          'Reply-To: info@linuxcounter.net' . "\r\n" .
          'X-Mailer: PHP/' . phpversion();
      mail("$to", "$betreff", "$text", "$header");
      if ($lico['send.admin.mails'] === true) {
        for ($a=0; $a<count($lico['adminmails']); $a++) {
            mail($lico['adminmails'][$a], "[lico] New password for \"".$lico['POST']['email']."\"", "Hello admin,\n".$lico['POST']['email']." has just requested a new password.\n", "$header");
        }
      }
      $iserror = 0;
    } else {
      $iserror = 1;
      $error[] = lico_lang('forgotten', 'email.not.found');
    }
  }
} else if (isset($lico['POST']['action']) && trim($lico['POST']['action']) == "newmail") {
  if (!isset($lico['POST']['userid']) || trim($lico['POST']['userid']) == "" || intval($lico['POST']['userid']) <= 0) {
    $iserror = 1;
    $error[] = lico_lang('forgotten', 'userid.not.entered');
  } else if (!isset($lico['POST']['oldemail']) || trim($lico['POST']['oldemail']) == "") {
    $iserror = 1;
    $error[] = lico_lang('forgotten', 'oldemail.not.entered');
  } else if (!isset($lico['POST']['newemail']) || trim($lico['POST']['newemail']) == "") {
    $iserror = 1;
    $error[] = lico_lang('forgotten', 'newemail.not.entered');
  } else if (!lico_ValidateEmail($lico['POST']['newemail'])) {
    $iserror = 1;
    $error[] = lico_lang('forgotten', 'newemail.wrong');
  } else {
    $select = "SELECT * FROM `users` WHERE `f_key`='".lico_ESC(intval($lico['POST']['userid']))."' AND `email`='".trim($lico['POST']['oldemail'])."'";
    $seluser = $db->unbuffered_query_first($select);
    if (isset($seluser[0]) && intval($seluser[0]) >= 1) {
      $newpasswd = lico_GenRandomString(8, PWD_ALLOW_ALL);
      $cnewpasswd = md5($newpasswd);
      $db->unbuffered_query("UPDATE `users` SET `f_mtime`='".date("Y-m-d H:i:s", time())."', `login`='".lico_ESC($cnewpasswd)."', `email`='".trim($lico['POST']['newemail'])."' WHERE `f_key`='".intval($seluser[0])."';");
      $success[] = lico_lang('forgotten', 'new.password.sent');
      $to = trim($lico['POST']['newemail']);
      $betreff = lico_lang('forgotten', 'new.email.subject');
      $text = lico_lang('forgotten', 'new.email.body');
      $text = str_replace("#EMAIL#", intval($seluser[0]), $text);
      $text = str_replace("#PASSWORD#", $newpasswd, $text);
      $header = 'From: "LinuxCounter.net" <noreply@linuxcounter.net>' . "\r\n" .
          'Reply-To: info@linuxcounter.net' . "\r\n" .
          'X-Mailer: PHP/' . phpversion();
      mail("$to", "$betreff", "$text", "$header");
      if ($lico['send.admin.mails'] === true) {
        for ($a=0; $a<count($lico['adminmails']); $a++) {
            mail($lico['adminmails'][$a], "[lico] New email for \"".$lico['POST']['oldemail']."\"", "Hello admin,\n".$lico['POST']['oldemail']." has just changed his email address to \"".$lico['POST']['newemail']."\".\n", "$header");
        }
      }
      $iserror = 0;
    } else {
      $iserror = 1;
      $error[] = lico_lang('forgotten', 'email.and.userid.not.found');
    }
  }
} else if (isset($lico['POST']['action']) && trim($lico['POST']['action']) == "sendmessage") {
  
  
  if (!isset($lico['POST']['userid']) || trim($lico['POST']['userid']) == "" || intval($lico['POST']['userid']) <= 0) {
    $iserror = 1;
    $error[] = lico_lang('forgotten', 'userid.not.entered');
  } else if (!isset($lico['POST']['city']) || trim($lico['POST']['city']) == "") {
    $iserror = 1;
    $error[] = lico_lang('forgotten', 'city.not.entered');
  } else if (!isset($lico['POST']['name']) || trim($lico['POST']['name']) == "") {
    $iserror = 1;
    $error[] = lico_lang('forgotten', 'name.not.entered');
  } else if (!isset($lico['POST']['country']) || trim($lico['POST']['country']) == "") {
    $iserror = 1;
    $error[] = lico_lang('forgotten', 'country.not.entered');
  } else if (!isset($lico['POST']['city']) || trim($lico['POST']['city']) == "") {
    $iserror = 1;
    $error[] = lico_lang('forgotten', 'city.not.entered');
  } else if (!isset($lico['POST']['email']) || trim($lico['POST']['email']) == "") {
    $iserror = 1;
    $error[] = lico_lang('forgotten', 'email.not.entered');
  } else if (!lico_ValidateEmail($lico['POST']['email'])) {
    $iserror = 1;
    $error[] = lico_lang('forgotten', 'email.wrong');
  } else if (!isset($lico['POST']['body']) || trim($lico['POST']['body']) == "") {
    $iserror = 1;
    $error[] = lico_lang('forgotten', 'body.not.entered');
  } else {
    $lico['POST']['body'] = stripslashes(trim($lico['POST']['body']));
    $success[] = lico_lang('forgotten', 'message.sent');
    $betreff = lico_lang('forgotten', 'message.subject');
    $text = lico_lang('forgotten', 'message.body');
    $text = str_replace("#USERNAME#", trim($lico['POST']['name']), $text);
    $text = str_replace("#USERID#", trim($lico['POST']['userid']), $text);
    $text = str_replace("#USERCITY#", trim($lico['POST']['city']), $text);
    $text = str_replace("#USERCOUNTRY#", trim($lico['POST']['country']), $text);
    $text = str_replace("#USEREMAIL#", trim($lico['POST']['email']), $text);
    $text = str_replace("#USERMESSAGE#", trim($lico['POST']['body']), $text);
    $header = 'From: "'.trim($lico['POST']['name']).'" <'.$lico['POST']['email'].'>' . "\r\n" .
        'X-Mailer: PHP/' . phpversion();
    for ($a=0; $a<count($lico['adminmails']); $a++) {
      $to = $lico['adminmails'][$a];
      mail("$to", "[LiCo] HELP NEEDED: $betreff", "$text", "$header");
    }
    $iserror = 0;
  }
} else if (isset($lico['POST']['action']) && trim($lico['POST']['action']) == "contactus") {
  
  
  if (!isset($lico['POST']['name']) || trim($lico['POST']['name']) == "") {
    $iserror = 1;
    $error[] = lico_lang('forgotten', 'name.not.entered');
  } else if (!isset($lico['POST']['email']) || trim($lico['POST']['email']) == "") {
    $iserror = 1;
    $error[] = lico_lang('forgotten', 'email.not.entered');
  } else if (!lico_ValidateEmail($lico['POST']['email'])) {
    $iserror = 1;
    $error[] = lico_lang('forgotten', 'email.wrong');
  } else if (!isset($lico['POST']['body']) || trim($lico['POST']['body']) == "") {
    $iserror = 1;
    $error[] = lico_lang('forgotten', 'body.not.entered');
  } else {
    $lico['POST']['body'] = stripslashes(trim($lico['POST']['body']));
    $success[] = lico_lang('forgotten', 'message.sent');
    $betreff = lico_lang('forgotten', 'message.subject');
    $text = lico_lang('forgotten', 'message.body');
    $text = str_replace("#USERNAME#", trim($lico['POST']['name']), $text);
    $text = str_replace("#USERID#", trim($lico['POST']['userid']), $text);
    $text = str_replace("#USERCITY#", trim($lico['POST']['city']), $text);
    $text = str_replace("#USERCOUNTRY#", trim($lico['POST']['country']), $text);
    $text = str_replace("#USEREMAIL#", trim($lico['POST']['email']), $text);
    $text = str_replace("#USERMESSAGE#", trim($lico['POST']['body']), $text);
    $header = 'From: "'.trim($lico['POST']['name']).'" <'.$lico['POST']['email'].'>' . "\r\n" .
        'X-Mailer: PHP/' . phpversion();
    for ($a=0; $a<count($lico['adminmails']); $a++) {
      $to = $lico['adminmails'][$a];
      mail("$to", "[LiCo] CONTACT REQUESTED: $betreff", "$text", "$header");
    }
    $iserror = 0;
  }
}



if (isset($_POST['lico']['action']) && trim($_POST['lico']['action']) == "setprofile") {
  $select = "SELECT * FROM `users` WHERE `f_key`!='".lico_ESC(intval($_SESSION['userid']))."' AND `username`='".lico_ESC($lico['POST']['myusername'])."'";
  $selusern = $db->unbuffered_query_first($select);
  if (isset($selusern[0]) && intval($selusern[0]) >= 1) {
    $error[] = lico_lang('general', 'username.exists');
    $iserror = 1;
  } else {
    if (isset($lico['POST']['myemail']) && lico_ValidateEmail($lico['POST']['myemail'])) {
      $email = ", `email`='".addslashes(trim($lico['POST']['myemail']))."'";
    } else {
      $email = "";
    }
    $started = "";
    if (isset($lico['POST']['started_month']) && trim($lico['POST']['started_month']) != "") {
      $started .= trim($lico['POST']['started_month']);
    }
    if (isset($lico['POST']['started_year']) && intval($lico['POST']['started_year']) >= 1991) {
      if ($started != "") $started .= " ";
      $started .= intval($lico['POST']['started_year']);
    }
    $usage = "";
    if (isset($lico['POST']['usage']) && count($lico['POST']['usage']) >= 1) {
      for ($i=0; $i<count($lico['POST']['usage']); $i++) {
        if ($usage!="") $usage .= ", ";
        $usage .= trim($lico['POST']['usage'][$i]);
      }
    }
    
    $country = $lico['POST']['mycountry'];
    $country = strtoupper(stripslashes(trim($country)));
    
    unset($retpc);
    $selpc = "SELECT `country` FROM `persons` WHERE `f_key`='".lico_ESC(intval($_SESSION['userid']))."' LIMIT 0,1;";
    $retpc = $db->aselect($selpc);
    $oldcountry = strtoupper(stripslashes(trim($retpc[0]['country'])));
    if ($oldcountry != "") {
      unset($retplace);
      $selplace = "SELECT * FROM `places` WHERE `code`='".lico_ESC($oldcountry)."' LIMIT 0,1;";
      $retplace = $db->aselect($selplace);
      if (isset($retplace[0]['f_key']) && intval($retplace[0]['f_key']) >= 1) {
        $updplace = "UPDATE `places` SET `users`=`users`-1 WHERE `code`='".lico_ESC($oldcountry)."'";
        $db->query($updplace);
      } else {
        $oldcountry = "";
      }
    }
    
    unset($retplace);
    $selplace = "SELECT * FROM `places` WHERE `code`='".lico_ESC($country)."' LIMIT 0,1;";
    $retplace = $db->aselect($selplace);
    if (isset($retplace[0]['f_key']) && intval($retplace[0]['f_key']) >= 1) {
      $updplace = "UPDATE `places` SET `users`=`users`+1 WHERE `code`='".lico_ESC($country)."'";
      $db->query($updplace);
    } else {
      $country = "";
    }
    
    $upd = "UPDATE `users` SET `f_mtime`='".date("Y-m-d H:i:s", time())."', `openid`='".lico_ESC($lico['POST']['openid'])."', `username`='".lico_ESC($lico['POST']['myusername'])."', `privacy`='".lico_ESC($lico['POST']['publishemail'])."'".$email." WHERE `f_key`='".lico_ESC(intval($_SESSION['userid']))."';";
    $db->unbuffered_query($upd);
    $upd = "UPDATE `persons` SET `f_mtime`='".date("Y-m-d H:i:s", time())."', `name`='".lico_ESC($lico['POST']['myname'])."', `city`='".lico_ESC($lico['POST']['mycity'])."', `state`='".lico_ESC($lico['POST']['mystate'])."', `country`='".lico_ESC($country)."', `homepage`='".lico_ESC($lico['POST']['myhomepage'])."', `started`='".lico_ESC($started)."', `usage`='".lico_ESC($usage)."', `may_publish`='".lico_ESC($lico['POST']['publishinfo'])."'".$email." WHERE `f_key`='".lico_ESC(intval($_SESSION['userid']))."';";
    $db->unbuffered_query($upd);
    $success[] = lico_lang('profile', 'data.successfully.saved');
    $iserror = 0;
  }
}




if (isset($_POST['lico']['action']) && trim($_POST['lico']['action']) == "deleteaccount") {
  
  lico_SetUserState(intval($_SESSION['userid']), 99);
  
  $success[] = lico_lang('profile', 'account.successfully.deleted');
  $iserror = 0;
  unset($lico['COOKIE']['pwd']);
  unset($lico['COOKIE']['num']);
  unset($lico['user']);
  unset($_SESSION['email']);
  $_SESSION['loggedin'] = false;
  $_SESSION['userid'] = 0;
  if (!isset($_SESSION['lang'])) {
    $_SESSION['lang'] = lico_getLangfromBrowser();
  }
  lico_delcookies();
}






if (isset($_POST['lico']['action']) && trim($_POST['lico']['action']) == "setprefs") {
  
  $timezone = (float)$_POST['lico']['timezone'];
  $dateformat = trim($_POST['lico']['dateformat']);
  $timeformat = trim($_POST['lico']['timeformat']);
  
  $selup = "SELECT * FROM `user_pref` WHERE `f_key`='".lico_ESC($_SESSION['userid'])."' AND `variable`='timezone';";
	$retup = $db->getAll_assoc($selup);
	if (count($retup) >= 1) {
    $upd = "UPDATE `user_pref` SET `value`='".$timezone."' WHERE `f_key`='".lico_ESC(intval($_SESSION['userid']))."' AND `variable`='timezone';";
    $db->unbuffered_query($upd);
  } else {
    $upd = "INSERT INTO `user_pref` SET `f_key`='".lico_ESC(intval($_SESSION['userid']))."', `variable`='timezone', `value`='".lico_ESC($timezone)."';";
    $db->unbuffered_query($upd);
  }
  
  $selup = "SELECT * FROM `user_pref` WHERE `f_key`='".lico_ESC($_SESSION['userid'])."' AND `variable`='dateformat';";
	$retup = $db->getAll_assoc($selup);
	if (count($retup) >= 1) {
    $upd = "UPDATE `user_pref` SET `value`='".lico_ESC($dateformat)."' WHERE `f_key`='".lico_ESC(intval($_SESSION['userid']))."' AND `variable`='dateformat';";
    $db->unbuffered_query($upd);
  } else {
    $upd = "INSERT INTO `user_pref` SET `f_key`='".lico_ESC(intval($_SESSION['userid']))."', `variable`='dateformat', `value`='".lico_ESC($dateformat)."';";
    $db->unbuffered_query($upd);
  }
  
  $selup = "SELECT * FROM `user_pref` WHERE `f_key`='".lico_ESC($_SESSION['userid'])."' AND `variable`='timeformat';";
	$retup = $db->getAll_assoc($selup);
	if (count($retup) >= 1) {
    $upd = "UPDATE `user_pref` SET `value`='".lico_ESC($timeformat)."' WHERE `f_key`='".lico_ESC(intval($_SESSION['userid']))."' AND `variable`='timeformat';";
    $db->unbuffered_query($upd);
  } else {
    $upd = "INSERT INTO `user_pref` SET `f_key`='".lico_ESC(intval($_SESSION['userid']))."', `variable`='timeformat', `value`='".lico_ESC($timeformat)."';";
    $db->unbuffered_query($upd);
  }
  
  
  $success[] = lico_lang('profile', 'prefs.successfully.saved');
}









if (isset($_POST['lico']['action']) && trim($_POST['lico']['action']) == "addmachine") {
  
  $cpu = trim($lico['POST']['cpu']);
  if (preg_match("`@`", $cpu)) {
    $tmp = explode("@", $cpu);
    $cpu = trim($tmp[0]);
    $herz = trim($tmp[1]);
    $cpu = preg_replace("`\s+`", " ", $cpu);
    $herz = preg_replace("`\s*\(.*$`", "", $herz);
    $herz = str_replace("+", "", $herz);
    $herz = str_replace("XP", "", $herz);
    $herz = str_replace("xp", "", $herz);
    if (preg_match("`^X[0-9]+`", trim($herz))) {
      $array['model_name'] .= " ".trim($herz);
      $herz = "";
    }
    $herz = str_replace("X", "", $herz);
    $herz = str_replace("x", "", $herz);
    if (preg_match("`@`", trim($herz))) {
      $tmp = explode("@", $herz);
      $array['model_name'] .= " ".trim($tmp[0]);
      $herz = trim($tmp[1]);
    }
    if (preg_match("`^P`", trim($herz)) || preg_match("`^T`", trim($herz))) {
      $array['model_name'] .= " ".trim($herz);
      $herz = "";
    }

    $herz = str_replace("P", "", $herz);
    $herz = str_replace("p", "", $herz);
    $herz = str_replace("?", "", $herz);
		if (preg_match("`mhz`i", $herz)) {
  		$herz = str_replace("mhz", "", trim($herz));
  		$herz = str_replace("MHz", "", trim($herz));
  		$herz = str_replace("MHZ", "", trim($herz));
  		$herz = str_replace("Mhz", "", trim($herz));
      $herz = str_replace(".", "", $herz);
      $herz = str_replace(",", "", $herz);
  		$herz = str_replace(" ", "", trim($herz));
    } else if (preg_match("`ghz`i", $herz)) {
  		$herz = str_replace("ghz", "", trim($herz));
  		$herz = str_replace("GHz", "", trim($herz));
  		$herz = str_replace("GHZ", "", trim($herz));
  		$herz = str_replace("Ghz", "", trim($herz));
      $herz = str_replace(",", ".", $herz);
  		$herz = str_replace(" ", "", trim($herz));
  		$herz = (float)$herz;
  		$herz = intval(($herz * 1000));
    } else if (preg_match("`gh`i", $herz)) {
  		$herz = str_replace("gh", "", trim($herz));
  		$herz = str_replace("GH", "", trim($herz));
  		$herz = str_replace("GH", "", trim($herz));
  		$herz = str_replace("Gh", "", trim($herz));
      $herz = str_replace(",", ".", $herz);
  		$herz = str_replace(" ", "", trim($herz));
  		$herz = (float)$herz;
  		$herz = intval(($herz * 1000));
		} else if (preg_match("`hz`i", $herz)) {
  		$herz = str_replace("hz", "", trim($herz));
  		$herz = str_replace("Hz", "", trim($herz));
  		$herz = str_replace("HZ", "", trim($herz));
      $herz = str_replace(".", "", $herz);
      $herz = str_replace(",", "", $herz);
  		$herz = str_replace(" ", "", trim($herz));
  		$herz = round(intval($herz)/1000);
		}
	}
	$cpu = preg_replace("`\s+`", " ", $cpu);
  $update_key = lico_GenRandomString(24, PWD_ALLOW_ALL);
  
  $select = "SELECT * FROM `processors` WHERE `name`='".lico_ESC($cpu)."' AND `herz`='".lico_ESC($herz)."'";
  $seluser = $db->unbuffered_query_first($select);
  if (isset($seluser[0]) && intval($seluser[0]) >= 1) {
    $cpuid = intval($seluser[0]);
    $upd = "UPDATE `processors` SET `machines`=`machines`+1 WHERE `f_key`='".$cpuid."'";
    $db->unbuffered_query($upd);
  } else {
    $ins = "INSERT INTO `processors` SET `name`='".lico_ESC($cpu)."', `herz`='".lico_ESC($herz)."', `machines`=1;";
    $db->unbuffered_query($ins);
    $select = "SELECT * FROM `processors` WHERE `name`='".lico_ESC($cpu)."' AND `herz`='".lico_ESC($herz)."'";
    $seluser = $db->unbuffered_query_first($select);
    $cpuid = intval($seluser[0]);
  }
  $purposes = "";
  for ($a=0; $a<count($lico['POST']['purpose']); $a++) {
    if ($purposes != "") $purposes .= ",";
    $purposes .= trim($lico['POST']['purpose'][$a]);
  }
  if (isset($lico['POST']['alternatepurpose']) && trim($lico['POST']['alternatepurpose']) != "") {
    if ($purposes != "") $purposes .= ",";
    $purposes .= trim($lico['POST']['alternatepurpose']);
  }
  
  
    $issetcountry = 0;
    $country = $lico['POST']['country'];
    $country = strtoupper(stripslashes(trim($country)));
    if ($country != "")
      $issetcountry = 1;
    
    unset($retplace);
    $selplace = "SELECT * FROM `places` WHERE `code`='".lico_ESC($country)."' LIMIT 0,1;";
    $retplace = $db->aselect($selplace);
    if (isset($retplace[0]['f_key']) && intval($retplace[0]['f_key']) >= 1) {
      $updplace = "UPDATE `places` SET `hostcount`=`hostcount`+1 WHERE `code`='".lico_ESC($country)."'";
      $db->query($updplace);
    } else {
      $country = "";
      if ($issetcountry == 1)
        $error[] = lico_lang('general', 'wrong.country');
    }
  
  $now = time();
  $insert = "INSERT INTO `machines` SET 
                    `f_ctime`='".date("Y-m-d H:i:s", $now)."', 
                    `f_mtime`='".date("Y-m-d H:i:s", $now)."', 
                    `owner`='".lico_ESC(intval($_SESSION['userid']))."', 
                    `name`='".lico_ESC($lico['POST']['name'])."', 
                    `cpu`='".lico_ESC($cpuid)."', 
                    `cpunum`='".lico_ESC($lico['POST']['cpunum'])."', 
                    `accounts`='0', 
                    `country`='".lico_ESC($country)."', 
                    `disk`='0', 
                    `distribution`='".lico_ESC($lico['POST']['distribution'])."', 
                    `distversion`='".lico_ESC($lico['POST']['distversion'])."', 
                    `mailer`='".lico_ESC($lico['POST']['mailer'])."', 
                    `memory`='0', 
                    `network`='".lico_ESC($lico['POST']['network'])."', 
                    `purpose`='".lico_ESC($purposes)."', 
                    `source`='', 
                    `users`='0', 
                    `sysclass`='".lico_ESC($lico['POST']['sysclass'])."',
                    `cpuflags`='',
                    `arch`='".lico_ESC($lico['POST']['arch'])."',
                    `kernel`='".lico_ESC($lico['POST']['kernel'])."',
                    `online`='offline',
                    `memfree`='0',
                    `swap`='0',
                    `swapfree`='0',
                    `diskfree`='0',
                    `update_key`='".lico_ESC($update_key)."',
                    `publish_hostname`='".lico_ESC($lico['POST']['publish_hostname'])."',
                    `publish_versions`='".lico_ESC($lico['POST']['publish_versions'])."',
                    `publish_cpuinfo`='".lico_ESC($lico['POST']['publish_cpuinfo'])."',
                    `publish_sizeinfo`='".lico_ESC($lico['POST']['publish_sizeinfo'])."', 
                    `isactive`='YES'
  ";
  $db->unbuffered_query($insert);
  
  $selkey = "SELECT `f_key` FROM `machines` WHERE `f_ctime`='".date("Y-m-d H:i:s", $now)."' AND `owner`='".lico_ESC(intval($_SESSION['userid']))."' AND `name`='".lico_ESC($lico['POST']['name'])."' AND `cpu`='".lico_ESC($cpuid)."' AND `kernel`='".lico_ESC($lico['POST']['kernel'])."' ORDER BY `f_key` DESC LIMIT 0,1";
  $retkey = $db->getAll_assoc($selkey);
  $f_key = strtoupper(stripslashes(trim($retp[0]['f_key'])));
  
  lico_SetMachineState($f_key, 1);
  
  $success[] = lico_lang('profile', 'machine.successfully.added');
}


if (isset($_POST['lico']['action']) && trim($_POST['lico']['action']) == "massaddmachines1") {
  if (!isset($_POST['lico']['createnum']) || intval($_POST['lico']['createnum']) <= 0) {
    
  } else {
    $nummachines = intval($_POST['lico']['createnum']);
    $creationtime = time();
    $_SESSION['creationtime'] = $creationtime;
    $cpu = trim($lico['POST']['cpu']);
    if (preg_match("`@`", $cpu)) {
      $tmp = explode("@", $cpu);
      $cpu = trim($tmp[0]);
      $herz = trim($tmp[1]);
      $cpu = preg_replace("`\s+`", " ", $cpu);
      $herz = preg_replace("`\s*\(.*$`", "", $herz);
      $herz = str_replace("+", "", $herz);
      $herz = str_replace("XP", "", $herz);
      $herz = str_replace("xp", "", $herz);
      if (preg_match("`^X[0-9]+`", trim($herz))) {
        $array['model_name'] .= " ".trim($herz);
        $herz = "";
      }
      $herz = str_replace("X", "", $herz);
      $herz = str_replace("x", "", $herz);
      if (preg_match("`@`", trim($herz))) {
        $tmp = explode("@", $herz);
        $array['model_name'] .= " ".trim($tmp[0]);
        $herz = trim($tmp[1]);
      }
      if (preg_match("`^P`", trim($herz)) || preg_match("`^T`", trim($herz))) {
        $array['model_name'] .= " ".trim($herz);
        $herz = "";
      }
  
      $herz = str_replace("P", "", $herz);
      $herz = str_replace("p", "", $herz);
      $herz = str_replace("?", "", $herz);
  		if (preg_match("`mhz`i", $herz)) {
    		$herz = str_replace("mhz", "", trim($herz));
    		$herz = str_replace("MHz", "", trim($herz));
    		$herz = str_replace("MHZ", "", trim($herz));
    		$herz = str_replace("Mhz", "", trim($herz));
        $herz = str_replace(".", "", $herz);
        $herz = str_replace(",", "", $herz);
    		$herz = str_replace(" ", "", trim($herz));
      } else if (preg_match("`ghz`i", $herz)) {
    		$herz = str_replace("ghz", "", trim($herz));
    		$herz = str_replace("GHz", "", trim($herz));
    		$herz = str_replace("GHZ", "", trim($herz));
    		$herz = str_replace("Ghz", "", trim($herz));
        $herz = str_replace(",", ".", $herz);
    		$herz = str_replace(" ", "", trim($herz));
    		$herz = (float)$herz;
    		$herz = intval(($herz * 1000));
      } else if (preg_match("`gh`i", $herz)) {
    		$herz = str_replace("gh", "", trim($herz));
    		$herz = str_replace("GH", "", trim($herz));
    		$herz = str_replace("GH", "", trim($herz));
    		$herz = str_replace("Gh", "", trim($herz));
        $herz = str_replace(",", ".", $herz);
    		$herz = str_replace(" ", "", trim($herz));
    		$herz = (float)$herz;
    		$herz = intval(($herz * 1000));
  		} else if (preg_match("`hz`i", $herz)) {
    		$herz = str_replace("hz", "", trim($herz));
    		$herz = str_replace("Hz", "", trim($herz));
    		$herz = str_replace("HZ", "", trim($herz));
        $herz = str_replace(".", "", $herz);
        $herz = str_replace(",", "", $herz);
    		$herz = str_replace(" ", "", trim($herz));
    		$herz = round(intval($herz)/1000);
  		}
  	}
  	$cpu = preg_replace("`\s+`", " ", $cpu);
    $select = "SELECT * FROM `processors` WHERE `name`='".lico_ESC($cpu)."' AND `herz`='".lico_ESC($herz)."'";
    $seluser = $db->unbuffered_query_first($select);
    if (isset($seluser[0]) && intval($seluser[0]) >= 1) {
      $cpuid = intval($seluser[0]);
      $upd = "UPDATE `processors` SET `machines`=`machines`+".$nummachines." WHERE `f_key`='".$cpuid."'";
      $db->unbuffered_query($upd);
    } else {
      $ins = "INSERT INTO `processors` SET `name`='".lico_ESC($cpu)."', `herz`='".lico_ESC($herz)."', `machines`=".$nummachines.";";
      $db->unbuffered_query($ins);
      $select = "SELECT * FROM `processors` WHERE `name`='".lico_ESC($cpu)."' AND `herz`='".lico_ESC($herz)."'";
      $seluser = $db->unbuffered_query_first($select);
      $cpuid = intval($seluser[0]);
    }
    $purposes = "";
    for ($a=0; $a<count($lico['POST']['purpose']); $a++) {
      if ($purposes != "") $purposes .= ",";
      $purposes .= trim($lico['POST']['purpose'][$a]);
    }
    if (isset($lico['POST']['alternatepurpose']) && trim($lico['POST']['alternatepurpose']) != "") {
      if ($purposes != "") $purposes .= ",";
      $purposes .= trim($lico['POST']['alternatepurpose']);
    }
    
    // $nummachines
    
    
    $fp = fopen("/srv/www.linuxcounter.net/massadd.log", "a");
    fwrite($fp, "[".date("Y-m-d H:i:s", time())."] nummachines=".$nummachines."\towner=".intval($_SESSION['userid'])."\tcpuid=".$cpuid."\tcpu=".$cpu."\therz=".$herz."\n");
    fclose($fp);
    chmod($logfile, 0777);
    
  
    $issetcountry = 0;
    $country = $lico['POST']['country'];
    $country = strtoupper(stripslashes(trim($country)));
    if ($country != "")
      $issetcountry = 1;
    
    unset($retplace);
    $selplace = "SELECT * FROM `places` WHERE `code`='".lico_ESC($country)."' LIMIT 0,1;";
    $retplace = $db->aselect($selplace);
    if (isset($retplace[0]['f_key']) && intval($retplace[0]['f_key']) >= 1) {
      $updplace = "UPDATE `places` SET `hostcount`=`hostcount`+".$nummachines." WHERE `code`='".lico_ESC($country)."'";
      $db->query($updplace);
    } else {
      $country = "";
      if ($issetcountry == 1)
        $error[] = lico_lang('general', 'wrong.country');
    }
    
    
    
    for ($mc=0; $mc<$nummachines; $mc++) {
      $update_key = lico_GenRandomString(24, PWD_ALLOW_ALL);
      $insert = "INSERT INTO `machines` SET 
                        `f_ctime`='".date("Y-m-d H:i:s", $creationtime)."', 
                        `f_mtime`='".date("Y-m-d H:i:s", $creationtime)."', 
                        `owner`='".lico_ESC(intval($_SESSION['userid']))."', 
                        `name`='Mass add #".($mc+1)."', 
                        `cpu`='".lico_ESC($cpuid)."', 
                        `cpunum`='".lico_ESC($lico['POST']['cpunum'])."', 
                        `accounts`='0', 
                        `country`='".lico_ESC($country)."', 
                        `disk`='0', 
                        `distribution`='".lico_ESC($lico['POST']['distribution'])."', 
                        `distversion`='".lico_ESC($lico['POST']['distversion'])."', 
                        `mailer`='".lico_ESC($lico['POST']['mailer'])."', 
                        `memory`='0', 
                        `network`='".lico_ESC($lico['POST']['network'])."', 
                        `purpose`='".lico_ESC($purposes)."', 
                        `source`='', 
                        `users`='0', 
                        `sysclass`='".lico_ESC($lico['POST']['sysclass'])."',
                        `cpuflags`='',
                        `arch`='".lico_ESC($lico['POST']['arch'])."',
                        `kernel`='".lico_ESC($lico['POST']['kernel'])."',
                        `online`='offline',
                        `swap`='0',
                        `update_key`='".lico_ESC($update_key)."',
                        `publish_hostname`='".lico_ESC($lico['POST']['publish_hostname'])."',
                        `publish_versions`='".lico_ESC($lico['POST']['publish_versions'])."',
                        `publish_cpuinfo`='".lico_ESC($lico['POST']['publish_cpuinfo'])."',
                        `publish_sizeinfo`='".lico_ESC($lico['POST']['publish_sizeinfo'])."', 
                        `isactive`='YES'
      ";
      $db->unbuffered_query($insert);
  
      $selkey = "SELECT `f_key` FROM `machines` WHERE `f_ctime`='".date("Y-m-d H:i:s", $creationtime)."' AND `owner`='".lico_ESC(intval($_SESSION['userid']))."' AND `name`='".lico_ESC($lico['POST']['name'])."' AND `cpu`='".lico_ESC($cpuid)."' AND `kernel`='".lico_ESC($lico['POST']['kernel'])."' ORDER BY `f_key` DESC LIMIT 0,1";
      $retkey = $db->getAll_assoc($selkey);
      $f_key = strtoupper(stripslashes(trim($retp[0]['f_key'])));
      
      lico_SetMachineState($f_key, 1);
      
    }
    $success[] = lico_lang('profile', 'machine.successfully.added');
  }
}




if (isset($_POST['lico']['oldpasswd']) && isset($_POST['lico']['firstpasswd']) && isset($_POST['lico']['secondpasswd']) && isset($_POST['lico']['action']) && trim($_POST['lico']['action']) == "changepasswd") {
  
  $oldpasswd = trim($_POST['lico']['oldpasswd']);
  $firstpasswd = trim($_POST['lico']['firstpasswd']);
  $secondpasswd = trim($_POST['lico']['secondpasswd']);
  if (strlen($firstpasswd) <= 4) {
    $error[] = lico_lang('profile', 'password.too.short');
    $iserror = 1;
  } else if ($firstpasswd != $secondpasswd) {
    $error[] = lico_lang('profile', 'passwords.do.not.match');
    $iserror = 1;
  } else {
    $select = "SELECT * FROM `users` WHERE `login`='".lico_ESC(md5($oldpasswd))."' AND `f_key`='".lico_ESC(intval($_SESSION['userid']))."'";
    $seluser = $db->unbuffered_query_first($select);
    if (!isset($seluser) || intval($seluser[0]) <= 0) {
      $error[] = lico_lang('profile', 'old.password.not.correct');
      $iserror = 1;
    } else {
      $upd = "UPDATE `users` SET `login`='".lico_ESC(md5($firstpasswd))."' WHERE `login`='".lico_ESC(md5($oldpasswd))."' AND `f_key`='".lico_ESC(intval($_SESSION['userid']))."'";
      $db->unbuffered_query($upd);
      $success[] = lico_lang('profile', 'password.successfully.changed');
      $iserror = 0;
    }
  }
}




if (isset($_POST['lico']['action']) && trim($_POST['lico']['action']) == "editmachine") {
  $machineid = intval($_POST['lico']['machineid']);
  
  $selcid = "SELECT * FROM `machines` WHERE `f_key`='".lico_ESC($machineid)."' AND `owner`='".lico_ESC($_SESSION['userid'])."'";
  $retcid = $db->unbuffered_query_first($selcid);
  if (isset($retcid[0]) && intval($retcid[0]) >= 1) {
    $oldcpu = intval($retcid[7]);
    
    $cpu = trim($lico['POST']['cpu']);
    if (preg_match("`@`", $cpu)) {
      $tmp = explode("@", $cpu);
      $cpu = trim($tmp[0]);
      $herz = trim($tmp[1]);
      $cpu = preg_replace("`\s+`", " ", $cpu);
      $herz = preg_replace("`\s*\(.*$`", "", $herz);
      $herz = str_replace("+", "", $herz);
      $herz = str_replace("XP", "", $herz);
      $herz = str_replace("xp", "", $herz);
      if (preg_match("`^X[0-9]+`", trim($herz))) {
        $array['model_name'] .= " ".trim($herz);
        $herz = "";
      }
      $herz = str_replace("X", "", $herz);
      $herz = str_replace("x", "", $herz);
      if (preg_match("`@`", trim($herz))) {
        $tmp = explode("@", $herz);
        $array['model_name'] .= " ".trim($tmp[0]);
        $herz = trim($tmp[1]);
      }
      if (preg_match("`^P`", trim($herz)) || preg_match("`^T`", trim($herz))) {
        $array['model_name'] .= " ".trim($herz);
        $herz = "";
      }
  
      $herz = str_replace("P", "", $herz);
      $herz = str_replace("p", "", $herz);
      $herz = str_replace("?", "", $herz);
  		if (preg_match("`mhz`i", $herz)) {
    		$herz = str_replace("mhz", "", trim($herz));
    		$herz = str_replace("MHz", "", trim($herz));
    		$herz = str_replace("MHZ", "", trim($herz));
    		$herz = str_replace("Mhz", "", trim($herz));
        $herz = str_replace(".", "", $herz);
        $herz = str_replace(",", "", $herz);
    		$herz = str_replace(" ", "", trim($herz));
      } else if (preg_match("`ghz`i", $herz)) {
    		$herz = str_replace("ghz", "", trim($herz));
    		$herz = str_replace("GHz", "", trim($herz));
    		$herz = str_replace("GHZ", "", trim($herz));
    		$herz = str_replace("Ghz", "", trim($herz));
        $herz = str_replace(",", ".", $herz);
    		$herz = str_replace(" ", "", trim($herz));
    		$herz = (float)$herz;
    		$herz = intval(($herz * 1000));
      } else if (preg_match("`gh`i", $herz)) {
    		$herz = str_replace("gh", "", trim($herz));
    		$herz = str_replace("GH", "", trim($herz));
    		$herz = str_replace("GH", "", trim($herz));
    		$herz = str_replace("Gh", "", trim($herz));
        $herz = str_replace(",", ".", $herz);
    		$herz = str_replace(" ", "", trim($herz));
    		$herz = (float)$herz;
    		$herz = intval(($herz * 1000));
  		} else if (preg_match("`hz`i", $herz)) {
    		$herz = str_replace("hz", "", trim($herz));
    		$herz = str_replace("Hz", "", trim($herz));
    		$herz = str_replace("HZ", "", trim($herz));
        $herz = str_replace(".", "", $herz);
        $herz = str_replace(",", "", $herz);
    		$herz = str_replace(" ", "", trim($herz));
    		$herz = round(intval($herz)/1000);
  		}
  	}
  	$cpu = preg_replace("`\s+`", " ", $cpu);
    $selcid = "SELECT `cpu` FROM `machines` WHERE `f_key`='".lico_ESC($machineid)."' AND `owner`='".lico_ESC($_SESSION['userid'])."'";
    $retcid = $db->unbuffered_query_first($selcid);
    $oldcpu = intval($retcid[0]);
    $select = "SELECT * FROM `processors` WHERE `name`='".lico_ESC($cpu)."' AND `herz`='".lico_ESC($herz)."'";
    $seluser = $db->unbuffered_query_first($select);
    if (isset($seluser[0]) && intval($seluser[0]) >= 1) {
      $cpuid = intval($seluser[0]);
      if ($oldcpu != $cpuid) {
        $upd = "UPDATE `processors` SET `machines`=`machines`+1 WHERE `f_key`='".$cpuid."'";
        $db->unbuffered_query($upd);
        $upd = "UPDATE `processors` SET `machines`=`machines`-1 WHERE `f_key`='".$oldcpu."'";
        $db->unbuffered_query($upd);
      }
    } else {
      $ins = "INSERT INTO `processors` SET `name`='".lico_ESC($cpu)."', `herz`='".lico_ESC($herz)."', `machines`=1;";
      $db->unbuffered_query($ins);
      $upd = "UPDATE `processors` SET `machines`=`machines`-1 WHERE `f_key`='".$oldcpu."'";
      $db->unbuffered_query($upd);
      $select = "SELECT * FROM `processors` WHERE `name`='".lico_ESC($cpu)."' AND `herz`='".lico_ESC($herz)."'";
      $seluser = $db->unbuffered_query_first($select);
      $cpuid = intval($seluser[0]);
    }
    $purposes = "";
    for ($a=0; $a<count($lico['POST']['purpose']); $a++) {
      if ($purposes != "") $purposes .= ",";
      $purposes .= trim($lico['POST']['purpose'][$a]);
    }
    if (isset($lico['POST']['alternatepurpose']) && trim($lico['POST']['alternatepurpose']) != "") {
      if ($purposes != "") $purposes .= ",";
      $purposes .= trim($lico['POST']['alternatepurpose']);
    }
    
    $issetcountry = 0;
    $country = $lico['POST']['country'];
    $country = strtoupper(stripslashes(trim($country)));
    if ($country != "")
      $issetcountry = 1;
      
    unset($retpc);
    $selpc = "SELECT `country` FROM `machines` WHERE `f_key`='".lico_ESC($machineid)."' AND `owner`='".lico_ESC($_SESSION['userid'])."' LIMIT 0,1;";
    $retpc = $db->aselect($selpc);
    $oldcountry = strtoupper(stripslashes(trim($retpc[0]['country'])));
    if ($oldcountry != "") {
      unset($retplace);
      $selplace = "SELECT * FROM `places` WHERE `code`='".lico_ESC($oldcountry)."' LIMIT 0,1;";
      $retplace = $db->aselect($selplace);
      if (isset($retplace[0]['f_key']) && intval($retplace[0]['f_key']) >= 1) {
        $updplace = "UPDATE `places` SET `hostcount`=`hostcount`-1 WHERE `code`='".lico_ESC($oldcountry)."'";
        $db->query($updplace);
      } else {
        $oldcountry = "";
      }
    }
    
    unset($retplace);
    $selplace = "SELECT * FROM `places` WHERE `code`='".lico_ESC($country)."' LIMIT 0,1;";
    $retplace = $db->aselect($selplace);
    if (isset($retplace[0]['f_key']) && intval($retplace[0]['f_key']) >= 1) {
      $updplace = "UPDATE `places` SET `hostcount`=`hostcount`+1 WHERE `code`='".lico_ESC($country)."'";
      $db->query($updplace);
    } else {
      $country = "";
      if ($issetcountry == 1)
        $error[] = lico_lang('general', 'wrong.country');
    }
    

    $upd = "UPDATE `machines` SET 
                      `f_mtime`='".date("Y-m-d H:i:s", time())."', 
                      `owner`='".lico_ESC(intval($_SESSION['userid']))."', 
                      `name`='".lico_ESC($lico['POST']['name'])."', 
                      `cpu`='".lico_ESC($cpuid)."', 
                      `cpunum`='".lico_ESC($lico['POST']['cpunum'])."', 
                      `country`='".lico_ESC($country)."', 
                      `distribution`='".lico_ESC($lico['POST']['distribution'])."', 
                      `distversion`='".lico_ESC($lico['POST']['distversion'])."', 
                      `mailer`='".lico_ESC($lico['POST']['mailer'])."', 
                      `network`='".lico_ESC($lico['POST']['network'])."', 
                      `purpose`='".lico_ESC($purposes)."', 
                      `sysclass`='".lico_ESC($lico['POST']['sysclass'])."',
                      `arch`='".lico_ESC($lico['POST']['arch'])."',
                      `kernel`='".lico_ESC($lico['POST']['kernel'])."',
                      `update_key`='".lico_ESC($lico['POST']['update_key'])."', 
                      `publish_hostname`='".lico_ESC($lico['POST']['publish_hostname'])."',
                      `publish_versions`='".lico_ESC($lico['POST']['publish_versions'])."',
                      `publish_cpuinfo`='".lico_ESC($lico['POST']['publish_cpuinfo'])."', 
                      `publish_sizeinfo`='".lico_ESC($lico['POST']['publish_sizeinfo'])."', 
                      `isactive`='".lico_ESC($lico['POST']['isactive'])."' 
             WHERE `f_key`='".lico_ESC($machineid)."' AND `owner`='".lico_ESC($_SESSION['userid'])."'
    ";
    $db->unbuffered_query($upd);
      
    lico_SetMachineState($machineid, $lico['POST']['isactive']);
      
    $success[] = lico_lang('profile', 'machine.successfully.edited');
    $iserror = 0;
  }
}


if (isset($_GET['a']) && isset($_GET['o']) && trim($_GET['a']) == "delete" && intval($_GET['o']) >= 1) {
  $selcid = "SELECT * FROM `machines` WHERE `f_key`='".lico_ESC(intval($_GET['o']))."' AND `owner`='".lico_ESC($_SESSION['userid'])."'";
  $retcid = $db->unbuffered_query_first($selcid);
  if (isset($retcid[0]) && intval($retcid[0]) >= 1) {
    lico_SetMachineState(intval($_GET['o']), 0);
    $db->unbuffered_query("DELETE FROM `machines` WHERE `f_key`='".lico_ESC(intval($_GET['o']))."' AND `owner`='".lico_ESC($_SESSION['userid'])."'");
    $success[] = lico_lang('profile', 'machine.successfully.deleted');
    $iserror = 0;
  } 
}



if (isset($_GET['a']) && isset($_GET['o']) && trim($_GET['a']) == "openiddel" && intval($_GET['o']) >= 1) {
  $selcid = "SELECT * FROM `openid` WHERE `id`='".lico_ESC(intval($_GET['o']))."' AND `owner`='".lico_ESC($_SESSION['userid'])."'";
  $retcid = $db->unbuffered_query_first($selcid);
  if (isset($retcid[0]) && intval($retcid[0]) >= 1) {
    $db->unbuffered_query("DELETE FROM `openid` WHERE `id`='".lico_ESC(intval($_GET['o']))."' AND `owner`='".lico_ESC($_SESSION['userid'])."'");
    $success[] = lico_lang('profile', 'openid.successfully.deleted');
    $iserror = 0;
  } 
}

if (!isset($_SESSION['browser']) && (!isset($cron))) {
  # if(ini_get("browscap")) {
    $_SESSION['browser'] = get_browser(null, true);
  # }
}



$restricted = array('profile', 'editprofile', 'editpref', 'changepasswd', 'addmachine', 'massaddmachine', 'deleteaccount');
if ($_SESSION['loggedin'] !== true) {
   if (isset($_REQUEST['c']) && in_array(trim($_REQUEST['c']), $restricted)) {
      $_REQUEST['c'] = "main";
      $_GET['c'] = "main";
      unset($_REQUEST['a']);
      unset($_GET['a']);
      $c = "main";
      $include = "main.inc.php";
      $error[] = lico_lang('general', 'no.access');
      $iserror = 1;
   }
}


$pagetitle = $lico['title'];
if (!isset($_REQUEST['c']) || trim($_REQUEST['c']) == "main") {
  $pagetitle = $lico['title'];
} else if (isset($_REQUEST['c']) && trim($_REQUEST['c']) == "about") {
  $pagetitle = "LiCo - About the project";
} else if (isset($_REQUEST['c']) && trim($_REQUEST['c']) == "addmachine") {
  $pagetitle = "LiCo - Add new machine";
} else if (isset($_REQUEST['c']) && trim($_REQUEST['c']) == "changelog") {
  $pagetitle = "LiCo - Project ChangeLog";
} else if (isset($_REQUEST['c']) && trim($_REQUEST['c']) == "changepasswd") {
  $pagetitle = "LiCo - Change your password";
} else if (isset($_REQUEST['c']) && trim($_REQUEST['c']) == "copyright") {
  $pagetitle = "LiCo - Copyright notices";
} else if (isset($_REQUEST['c']) && trim($_REQUEST['c']) == "disclaimer") {
  $pagetitle = "LiCo - Project disclaimer";
} else if (isset($_REQUEST['c']) && trim($_REQUEST['c']) == "editmachine") {
  $pagetitle = "LiCo - Edit a machine";
} else if (isset($_REQUEST['c']) && trim($_REQUEST['c']) == "editprofile") {
  $pagetitle = "LiCo - Edit your profile";
} else if (isset($_REQUEST['c']) && trim($_REQUEST['c']) == "forgotten") {
  $pagetitle = "LiCo - Lost password page";
} else if (isset($_REQUEST['c']) && trim($_REQUEST['c']) == "help") {
  $pagetitle = "LiCo - Project help and F.A.Q.";
} else if (isset($_REQUEST['c']) && trim($_REQUEST['c']) == "impressum") {
  $pagetitle = "LiCo - Project impressum";
} else if (isset($_REQUEST['c']) && trim($_REQUEST['c']) == "info") {
  $pagetitle = "LiCo - Project information";
} else if (isset($_REQUEST['c']) && trim($_REQUEST['c']) == "intention") {
  $pagetitle = "LiCo - Project intention";
} else if (isset($_REQUEST['c']) && trim($_REQUEST['c']) == "login") {
  $pagetitle = "LiCo - Login to your account";
} else if (isset($_REQUEST['c']) && trim($_REQUEST['c']) == "logout") {
  $pagetitle = "LiCo - Logout";
} else if (isset($_REQUEST['c']) && trim($_REQUEST['c']) == "machine") {
  $pagetitle = "LiCo - Public page of machine #".intval($_REQUEST['a'])."";
} else if (isset($_REQUEST['c']) && trim($_REQUEST['c']) == "massaddmachine") {
  $pagetitle = "LiCo - Add a lot of machines";
} else if (isset($_REQUEST['c']) && trim($_REQUEST['c']) == "news") {
  $pagetitle = "LiCo - Project news and announcements";
} else if (isset($_REQUEST['c']) && trim($_REQUEST['c']) == "privacy") {
  $pagetitle = "LiCo - Privacy policy";
} else if (isset($_REQUEST['c']) && trim($_REQUEST['c']) == "profile") {
  $pagetitle = "LiCo - User profile";
} else if (isset($_REQUEST['c']) && trim($_REQUEST['c']) == "register") {
  $pagetitle = "LiCo - Account registration";
} else if (isset($_REQUEST['c']) && trim($_REQUEST['c']) == "short") {
  $pagetitle = "LiCo - Linux counter summary report";
} else if (isset($_REQUEST['c']) && trim($_REQUEST['c']) == "machines") {
  $pagetitle = "LiCo - Linux Counter Machine Report";
} else if (isset($_REQUEST['c']) && trim($_REQUEST['c']) == "stats") {
  $pagetitle = "LiCo - Statistics";
} else if (isset($_REQUEST['c']) && trim($_REQUEST['c']) == "team") {
  $pagetitle = "LiCo - Project team";
} else if (isset($_REQUEST['c']) && trim($_REQUEST['c']) == "user") {
  $pagetitle = "LiCo - Public page for user #".intval($_REQUEST['a'])."";
}



if (!isset($_SESSION['numusers'])) {
  $select = "SELECT COUNT(*) AS num FROM `users` WHERE `state`=1";
  $seluser = $db->unbuffered_query_first($select);
  $_SESSION['numusers'] = intval($seluser[0]);
}
$numusers = $_SESSION['numusers'];
if (!isset($_SESSION['nummachines'])) {
  $select = "SELECT COUNT(m.f_key) AS num FROM `machines` m LEFT JOIN `users` u ON (u.`f_key`=m.`owner`) WHERE u.`state`=1 AND m.`isactive`='YES'";
  $selmach = $db->unbuffered_query_first($select);
  $_SESSION['nummachines'] = intval($selmach[0]);
}
$nummachines = $_SESSION['nummachines'];

$popcont = file($lico['temp_path']."population.db");
$popstr = trim($popcont[0]);
$iustr = trim($popcont[1]);
$tmp = explode("|", $popstr);
$pop = (float)$tmp[0];
$date = $tmp[1];
$rate = (float)$tmp[2];
$tmp = explode("/", $date);
$day = intval($tmp[1]);
$mon = intval($tmp[0]);
$year = intval($tmp[2]);
$oldts = gmmktime(0,0,0, $mon, $day, $year);
$diff = time() - $oldts;
$newhuman = $rate * $diff;
$aktpop = $pop + $newhuman;
$world_population                 =   round($aktpop);       // Number of all human beings on earth
$world_population_formatted       =   number_format($world_population);

$tmp = explode("|", $iustr);
$iupop = intval($tmp[0]);
$iudate = $tmp[1];
$iurate = (float)$tmp[2];
$tmp = explode("/", $iudate);
$day = intval($tmp[1]);
$mon = intval($tmp[0]);
$year = intval($tmp[2]);
$oldts = mktime(0,0,0, $mon, $day, $year);
$diff = time() - $oldts;
$newiusers = $iurate * $diff;
$aktiusers = $iupop + $newiusers;
$world_internet_users             =   round($aktiusers);    // Number of internet users on earth
$world_internet_users_formatted   =   number_format($world_internet_users);    // Number of internet users on earth

$estimated_num_of_linux_users     =   (($world_internet_users / 100) * $lico['average_linux_users_in_percent']);
$guestimate_users                 =   $estimated_num_of_linux_users;
$guestimate_users_formatted       = number_format($guestimate_users);














?>
